﻿/**
 * ...
 * @author Lucas Duroj
 */

package getengine.core;
import haxe.Timer;

class SceneManager
{
	inline static private var DEFAULT_FPS : Float = 60.0;
	
	//Singelton definition
	static public var instance (getInstance, null): SceneManager;
	static private function getInstance() : SceneManager
	{
		if (instance == null) instance = new SceneManager();
		return instance;
	}
	
	//Frame rate settings
	public var fps (getFps, setFps): Float;
	
	private var targetFps : Float;
	private var currentFps : Float;
	
	private var targetFrameTime : Float;
	private var frameDelta : Float;
	
	private var lastFrameTime : Float;
	
	//Scenes
	private var sceneList : Array<Scene>;
	
	private function new() 
	{
		sceneList = new Array<Scene>();
		lastFrameTime = 0;
		this.fps = SceneManager.DEFAULT_FPS;
	}
	
	//SceneList manipulators
	public function addScene(scene : Scene) : Void
	{
		sceneList.push(scene);
	}
	
	public function removeScene(scene : Scene) : Bool
	{
		return sceneList.remove(scene);
	}
	
	public function swapScene(swap : Scene, whit : Scene) : Bool
	{
		for (i in 0...sceneList.length) {
			if (sceneList[i] == swap) {
				sceneList[i] = whit;
				return true;
			}
		}
		
		return false;
	}
	
	//Frame rate
	private function setFps(value : Float) : Float // TODO: Change to setTargetFps ?
	{
		targetFps = value;
		targetFrameTime = 1.0 / value;
		
		return currentFps;
	}
	
	private function getFps() : Float
	{
		return currentFps;
	}
	
	//The frameloop root function
	public function update() : Void
	{
		//Calculate last frames fps
		var timePast = Timer.stamp() - lastFrameTime;
		currentFps =  1.0 / timePast;
		frameDelta = timePast / targetFrameTime;
		
		lastFrameTime = Timer.stamp();
		
		//Render visible sceneList
		for (scene in sceneList) {
			if(!scene.hidden)scene.update(frameDelta);
		}
		
		//Render visible sceneList
		for (scene in sceneList) {
			if(!scene.hidden)scene.render();
		}
	}
	
}